package com.ruoyi.web.controller.baodao.controller;

import com.ruoyi.baodao.entity.*;
import com.ruoyi.baodao.mapper.BDMapper;
import com.ruoyi.baodao.mapper.LinkTemplateMapper;
import com.ruoyi.baodao.mapper.MFGoods9999Mapper;
import com.ruoyi.baodao.mapper.MFGoodsLinkMapper;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


// 药品关系维护

@Slf4j
@Controller
@RequestMapping("baodao/demo01")
public class DemoController extends BaseController {
    @Autowired
    MFGoods9999Mapper mfGoods9999Mapper;
    @Autowired
    MFGoodsLinkMapper mfGoodsLinkMapper;
    @Autowired
    BDMapper bdMapper;
    @Autowired
    LinkTemplateMapper linkTemplateMapper;


    private String prefix = "baodao/demo01";

    @GetMapping()
    public String operlog()
    {
        return prefix + "/demo01";
    }

    /**
     * 药品主档
     */
    @PostMapping("/list")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public TableDataInfo list(MFGoods9999 mfGoods9999, String flag)
    {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        log.info("查询药品主档,标识参数flag ：{}",flag);
        logger.info("查询药品主档,参数:{}",mfGoods9999.getPlucode());
        logger.info("查询药品主档,参数:{}",mfGoods9999.getClassname());
        // 取所属药店下所有 关联药品信息
        MFGoodsLinkExample mfGoodsLinkExample = new MFGoodsLinkExample();
        MFGoodsLinkExample.Criteria criteria3 = mfGoodsLinkExample.createCriteria();
        criteria3.andShopidEqualTo(sysUser.getDept().getDeptName());
        List<MFGoodsLink> mfGoodsLinks = mfGoodsLinkMapper.selectByExample(mfGoodsLinkExample);

        startPage(); //分页

        MFGoods9999Example mfGoods9999Example = new MFGoods9999Example();
        MFGoods9999Example.Criteria criteria = mfGoods9999Example.createCriteria();
        if(mfGoods9999.getPlucode() != null && !mfGoods9999.getPlucode().equals("")){
        criteria.andPlucodeEqualTo(mfGoods9999.getPlucode());}
        if(mfGoods9999.getGoodscode() != null && !mfGoods9999.getGoodscode().equals("")){
            criteria.andGoodscodeEqualTo(mfGoods9999.getGoodscode());
        }
        if(mfGoods9999.getGoodsname() != null && !mfGoods9999.getGoodsname().equals("")){
        criteria.andGoodsnameLike("%" + mfGoods9999.getGoodsname() + "%");
    }
        if(mfGoods9999.getClassname() != null && !mfGoods9999.getClassname().equals("")){
            criteria.andClassnameEqualTo(mfGoods9999.getClassname());
        }

        // 所属药店下所有 关联药品信息 商品码 数组
        List<String> strings = new ArrayList<>();

        logger.info("药品关系表数据" + mfGoodsLinks.size());
        if(mfGoodsLinks != null && mfGoodsLinks.size() != 0)
        {
            for (MFGoodsLink m:
                mfGoodsLinks ) {
                strings.add(m.getGoodscode());
            }
        }

        criteria.andGoodscodeIn(strings);
        logger.info("药品关系表数据" + strings.toString());
      //  SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        // 取部门编号（门店号）
        sysUser.getDept();
        String shopId = sysUser.getDept().getDeptName();

        // 第二个参数为动态表名
       // mfGoodsLinkExample.set
       // List<MFGoods9999> mfGoods9999s =   mfGoods9999Mapper.selectByExample(mfGoods9999Example);
        List<MFGoods9999> mfGoods9999s =  bdMapper.queryGoods1(mfGoods9999.getGoodscode(),mfGoods9999.getGoodsname(),shopId,mfGoods9999.getClassname(),null,null);
        logger.info(mfGoods9999s.toString());

        // 统计 药品 推荐和关联 数量
/*        int num1 = 0;
        int num2 = 0;*/
        for (MFGoods9999 m:
             mfGoods9999s) {
            MFGoodsLinkExample goodsLinkExample = new MFGoodsLinkExample();
            MFGoodsLinkExample.Criteria criteria1 = goodsLinkExample.createCriteria();
            criteria1.andGoodscodeEqualTo(m.getGoodscode());
            criteria1.andShowflagEqualTo("1");
            criteria1.andShopidEqualTo(sysUser.getDept().getDeptName());
            long num1 = mfGoodsLinkMapper.countByExample(goodsLinkExample);
            m.setNum1((int) num1);
            MFGoodsLinkExample goodsLinkExample2 = new MFGoodsLinkExample();
            MFGoodsLinkExample.Criteria criteria2 = goodsLinkExample2.createCriteria();
            criteria2.andGoodscodeEqualTo(m.getGoodscode());
            criteria2.andShowflagEqualTo("2");
            criteria2.andShopidEqualTo(sysUser.getDept().getDeptName());
            long num2 = mfGoodsLinkMapper.countByExample(goodsLinkExample2);
            m.setNum2((int) num2);
        }

      //  List<MFGoods9999> mfGoods9999s1 = companyService.selectCompanyAll(company);
        return getDataTable(mfGoods9999s);

    }

    // 新增关联关系
    /**
     * 新增客户
     */
    //@GetMapping("/add/{id}")
    @GetMapping("/add")
   /* public String add(@PathVariable("id") String id)*/
    public String add(@RequestParam("id") String id, ModelMap modelMap)
    {
        modelMap.put("key01",id);
        logger.info("新增关联关系：" + id);
        return prefix + "/add";
    }

    // 编辑关联关系
    /**
     * 新增客户
     */
    @GetMapping("/edit")
    public String edit()
    {
        logger.info("编辑页面");
        return prefix + "/edit";
    }

    // 增加药品关系
    @PostMapping("/addGoodLink")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult addGoodLink(@Param("key1") String key1, @Param("key2") String key2, @Param("flag") String flag,@Param("templatename") String templateName){

        // 登录用户所在店号
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        log.info("调用增加药品关系接口,参数1：" + key1 + "  参数2：" + key2 );
        // 数据处理,
        // 以逗号分隔开的字符串转换成数组
        String[] key1Array = key1.split(",");
      //  String[] key2Array = key2.split(",");
        String[] key2Array ;
        List<LinkTemplate> linkTemplates = new ArrayList<>();

        // 用模板代替 key2
        if(!templateName.equals("") || templateName != null){
            logger.info("模板名：" + templateName);
            LinkTemplateExample linkTemplateExample = new LinkTemplateExample();
            LinkTemplateExample.Criteria criteria = linkTemplateExample.createCriteria();
            criteria.andShopidEqualTo(sysUser.getDept().getDeptName());
            criteria.andTemplatenameEqualTo(templateName);
             linkTemplates = linkTemplateMapper.selectByExample(linkTemplateExample);

             logger.info(linkTemplates.toString());

        }
        Date date = new Date();
        for(String s1 : key1Array){
            for (LinkTemplate template : linkTemplates ){
            MFGoodsLink goodsLink = new MFGoodsLink();
            goodsLink.setGoodscode(s1);
            goodsLink.setShopid(sysUser.getDept().getDeptName());
            goodsLink.setShowflag(template.getShowflag());
            goodsLink.setAddtime(date);
            goodsLink.setLinkgoodscode(template.getLinkgoodscode());
                try {
                    mfGoodsLinkMapper.insert(goodsLink);
                }catch (Exception e){
                    e.printStackTrace();
                    return error("异常");
                }
            }
        }
        return success("成功");
    }

    // 查询药品关联关系
    @PostMapping("/queryGoodsLink")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public List<MFGoods9999> queryGoodsLink(String goodsCode){
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        log.info("查询药品关联关系：参数1：" + goodsCode);
      //  goodsCode = "401-01-330";
        MFGoodsLinkExample goodsLinkExample = new MFGoodsLinkExample();
        MFGoodsLinkExample.Criteria criteria = goodsLinkExample.createCriteria();
        criteria.andShopidEqualTo(sysUser.getDept().getDeptName());
        criteria.andGoodscodeEqualTo(goodsCode);
        List<MFGoodsLink> mfGoodsLinks = mfGoodsLinkMapper.selectByExample(goodsLinkExample);
        // 查询结果
        List<MFGoods9999> mfGoods9999s = new ArrayList<>();
        for (MFGoodsLink mfgl:
            mfGoodsLinks ) {
            //MFGoods9999 mfGoods9999 = mfGoods9999Mapper.selectByPrimaryKey(new MFGoods9999Key("9999",mfgl.getLinkgoodscode()));

                List<MFGoods9999> list = bdMapper.queryGoods(mfgl.getLinkgoodscode(), null, sysUser.getDept().getDeptName(), null, null, null);
                // MFGoods9999 mfGoods9999 = bdMapper.queryGoods(mfgl.getGoodscode(),null,sysUser.getDept().getDeptName(),null,null,null);
                MFGoods9999 mfGoods9999 = list.get(0);
                mfGoods9999.setShowFlag(Integer.valueOf(mfgl.getShowflag()));
                if (mfGoods9999 != null) {
                    mfGoods9999s.add(mfGoods9999);
                }

        }
        log.info(mfGoods9999s.toString());
/*        MFGoods9999 testData = new MFGoods9999();
        testData.setGoodsname("测试");
        mfGoods9999s.add(testData);*/

        return  mfGoods9999s;
    }

    @PostMapping("/remove")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult remove(String ids)
    {
        logger.info("删除一条药品关联记录,药品内码：",ids);
        try
        {
           // return toAjax(roleService.deleteRoleByIds(ids));
            MFGoodsLinkExample mfGoodsLinkExample = new MFGoodsLinkExample();
            MFGoodsLinkExample.Criteria criteria = mfGoodsLinkExample.createCriteria();
            criteria.andGoodscodeEqualTo(ids);
            return  toAjax(mfGoodsLinkMapper.deleteByExample(mfGoodsLinkExample));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

}
